<template>
  <div class="note-editor">
    <!-- 标题和分类区域 -->
    <div class="note-header">
      <el-input
        v-model="noteTitle"
        placeholder="请输入标题"
        class="note-title-input"
        clearable
        @input="saveDraft"
      />
      <el-select v-model="selectedCategory" placeholder="选择分类" class="note-category-select" @change="saveDraft">
        <el-option
          v-for="category in categories"
          :key="category.value"
          :label="category.label"
          :value="category.value"
        />
      </el-select>
      <el-select v-model="selectedPrivacy" placeholder="选择公开性" class="note-category-select" @change="saveDraft">
        <el-option
          v-for="privacy in privacys"
          :key="privacy.value"
          :label="privacy.label"
          :value="privacy.value"
        />
      </el-select>
      <el-select
        v-model="tags"
        multiple
        filterable
        allow-create
        default-first-option
        :reserve-keyword="false"
        placeholder="选择或者添加你的标签"
        style="width: 340px"
        @change="saveDraft"
      >
        <el-option
          v-for="item in tagOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>

    <!-- 摘要和封面图片上传区域 -->
    <div class="note-summary-cover">
      <el-input
        v-model="noteSummary"
        placeholder="请输入文章摘要"
        type="textarea"
        :rows="3"
        clearable
        class="note-summary-input"
        @input="saveDraft"
      />
      <el-upload
        class="upload-demo"
        action=""
        :auto-upload="false"
        :file-list="fileList"
        list-type="picture-card"
        :limit="1"
        @change="handleChange"
        :on-preview="handlePreview"
      >
        <el-tooltip content="点击以上传封面图片" placement="top">
         <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
        </el-tooltip>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="封面预览" />
      </el-dialog>
    </div>

    <!-- Markdown 编辑器区域 -->
    <md-editor
      v-model="markdownContent"
      :preview="true"
      :theme="theme"
      class="md-editor"
      :previewTheme="'github'"
      @change="saveDraft"
    />

    <!-- 发布按钮 -->
    <div class="note-footer">
      <el-button type="primary" @click="publishNote">发布</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';
import { MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import { useDark } from '@vueuse/core';
import {getAction, postAction, uploadAction} from "@/api/manage";
import { Data } from "@/api/ajaxUrl.config";
import { Plus } from '@element-plus/icons-vue';
import {useRouter} from "vue-router";

const selectedPrivacy = ref('public')

// 公开性
const privacys = [
  { label: '公开', value: 'public' },
  { label: '仅关注用户可见', value: 'protected' },
  { label: '私有', value: 'private' },
];

// 笔记的分类
const noteTitle = ref('');
const noteSummary = ref('');
const selectedCategory = ref('');
const markdownContent = ref('');
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const tags = ref([]);
const tagOptions = ref([]);

// 封面图片上传功能
const handlePreview = (file: any) => {
  dialogImageUrl.value = file.url || URL.createObjectURL(file.raw);
  dialogVisible.value = true;
};

const handleChange = (file: any) => {
  fileList.value = [file];
  saveDraft();  // 每次上传图片后，保存草稿
};
  const router = useRouter()
// 发布笔记
const publishNote = () => {
  const formData = new FormData();
  formData.append('title', noteTitle.value);
  formData.append('summary', noteSummary.value);
  formData.append('category', selectedCategory.value);
  formData.append('tags', JSON.stringify(tags.value)); // 确保 tags 是 JSON 字符串
  formData.append('content', markdownContent.value);

  // 只在存在文件时添加封面
  if (fileList.value.length > 0) {
    console.log(fileList.value[0])
    formData.append('cover_image', fileList.value[0].raw); // 注意 raw 属性
  }

  formData.append('privacy', selectedPrivacy.value);

  postAction(Data.notes, formData).then((res) => {
    console.log('笔记发布成功：', res);
    router.push({ name: 'note' }); // 确保路由名称正确
    clearDraft(); // 发布后清除草稿
  });
};


// 本地存储草稿
const saveDraft = () => {
  const draft = {
    title: noteTitle.value,
    summary: noteSummary.value,
    category: selectedCategory.value,
    tags:  tags.value,
    content: markdownContent.value,
    cover_image: fileList.value,
    privacy: selectedPrivacy.value,
  };
  localStorage.setItem('noteDraft', JSON.stringify(draft));
};

// 加载草稿
const loadDraft = () => {
  const savedDraft = localStorage.getItem('noteDraft');
  if (savedDraft) {
    const draft = JSON.parse(savedDraft);
    noteTitle.value = draft.title || '';
    noteSummary.value = draft.summary || '';
    selectedCategory.value = draft.category || '';
    tags.value = draft.tags || [];
    markdownContent.value = draft.content || '';
    fileList.value = draft.cover_image || [];
    selectedPrivacy.value = draft.privacy || 'private';
  }
};

// 清除草稿
const clearDraft = () => {
  localStorage.removeItem('noteDraft');
};

// 处理主题切换
const isDark = useDark();
const theme = ref(isDark.value ? 'dark' : 'light');

// 监听主题切换
watch(isDark, (newValue) => {
  theme.value = newValue ? 'dark' : 'light';
});

// 分类选项
const categories = ref([]);
const getCategories = () => {
  getAction(Data.category, '').then((res: any) => {
    categories.value = res.results.map((item: any) => {
      item.label = item.name;
      item.value = item.id;
      return item;
    });
  });
};

// 获取标签
const getTags = () => {
  getAction(Data.tags, '').then((res: any) => {
    tagOptions.value = res.map((item: any) => {
      item.label = item.name;
      item.value = item.name;
      return item;
    });
  });
};

// 页面加载时加载草稿
onMounted(() => {
  getCategories();
  getTags();
  loadDraft(); // 加载草稿数据
});
</script>

<style scoped>
.note-editor {
  height: calc(100vh - 180px);
  padding: 20px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}

.note-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  height: 40px;
}

.note-title-input {
  flex: 3;
  margin-right: 20px;
}

.note-category-select {
  flex: 1;
  margin-right: 20px;
}

.note-tags-input {
  flex: 2;
}

.note-summary-cover {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.note-summary-input {
  flex: 3;
  margin-right: 20px;
}

.upload-demo {
  flex: 1;
}

.md-editor {
  flex: 1;
  margin-bottom: 20px;
  overflow-y: auto;
  text-align: left;
}

.note-footer {
  text-align: right;
  height: 40px;
}
</style>
